import Sortable from "sortablejs";
import { clone, delay } from "@pureadmin/utils";
import { tableDataDrag } from "./data";
import { ref, nextTick, onMounted, reactive } from "vue";

// 列拖拽演示
export function useColumns() {
  // clone(tableDataDrag, true)
  const dataList = ref([]);
  const select = ref(true);
  const loading = ref(true);
  const multipleSelection = reactive([]);
  // const tableSize = ref(0);
  const columns = ref<TableColumnList>([
    // {
    //   type: "selection",
    //   align: "left",
    //   hide: () => select.value
    // },
    // {
    //   label: "ID",
    //   prop: "id"
    // },
    // {
    //   label: "日期",
    //   prop: "date"
    // },
    // {
    //   label: "姓名",
    //   prop: "name"
    // },
    // {
    //   label: "操作",
    //   width: "120",
    //   fixed: "right",
    //   slot: "operation"
    // }
  ]);

  const columnDrop = (event: { preventDefault: () => void }) => {
    if (event && event.preventDefault) {
      event.preventDefault();
    }
    nextTick(() => {
      const wrapper: HTMLElement = document.querySelector(
        ".el-table__header-wrapper tr"
      );
      Sortable.create(wrapper, {
        animation: 300,
        delay: 0,
        onEnd: ({ newIndex, oldIndex }) => {
          const oldItem = columns.value[oldIndex];
          columns.value.splice(oldIndex, 1);
          columns.value.splice(newIndex, 0, oldItem);
        }
      });
    });
  };
  /** 分页配置 */
  const pagination = reactive({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    total: 0,
    align: "right",
    background: true,
    small: false
  });
  /** 加载动画配置 */
  const loadingConfig = reactive({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });

  function onSizeChange(val) {
    console.log("onSizeChange", val);
  }

  function onCurrentChange(val) {
    loadingConfig.text = `正在加载第${val}页...`;
    loading.value = true;
    delay(600).then(() => {
      loading.value = false;
    });
  }
  const toggleSelection = (rows?: any) => {
    const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
    if (rows) {
      rows.forEach(row => {
        toggleRowSelection(row, undefined);
      });
    } else {
      clearSelection();
    }
  };

  const handleSelectionChange = val => {
    multipleSelection.value = val;
  };

  onMounted(() => {
    pagination.total = dataList.value.length;
    nextTick(() => {
      columnDrop(event);
    });
  });

  return {
    columns,
    dataList,
    select,
    pagination,
    loading,
    loadingConfig,
    onSizeChange,
    onCurrentChange,
    multipleSelection,
    toggleSelection,
    handleSelectionChange
  };
}
